<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <right-toolbar :show-search.sync="showSearch" @queryTable="getList" /> -->
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" width="50" />
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="拥有权限" align="center" prop="roleName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-waves="['system:role:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-waves="['system:role:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate2(scope.row)"
          >权限配置</el-button>
          <el-button
            v-waves="['system:role:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 权限树 -->
    <el-dialog title="权限配置" :visible.sync="openTree" width="500px" append-to-body>
      <el-form label-width="80px">
        <el-tree
          ref="formTree"
          :data="data"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="checkedRole"
          :props="defaultProps"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormTree">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  getRoleList,
  getRoleOne,
  addRoleOne } from '@/api/system/role'
import waves from '@/directive/waves'

export default {
  name: 'Index',
  components: { },
  directives: { waves },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openTree: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null
      },
      // 表单参数
      form: {
        roleName: ''
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '请填写名称', trigger: 'blur' }
        ]
      },
      // tree数据
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      checkedRole: []
    }
  },
  created() {
    this.getList()
    this.apiGetList()
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listRole(this.queryParams).then(response => {
        this.roleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 权限列表
    apiGetList() {
      getRoleList().then(response => {
        console.log(response.data)
        const roleList = []
        response.data.forEach((item, index) => {
          roleList.push({
            id: item.id,
            label: item.name
          })
          if (item.children && item.children.length > 1) {
            roleList[index].children = []
            item.children.forEach(item => {
              roleList[index].children.push({
                id: item.id * 1,
                label: item.name
              })
            })
          }
        })
        this.data = roleList
        console.log(this.data)
        // const datas = response.data[0]
        // const a = datas.children[0].perms
        // console.log(JSON.parse(a))
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.openTree = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        roleName: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加角色'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRole(id).then(response => {
        this.form = {
          id: response.data.id,
          roleName: response.data.roleName
        }
        this.open = true
        this.title = '修改角色'
      })
    },
    // 权限配置
    handleUpdate2(row) {
      this.reset()
      const id = row.id || this.ids
      this.form.id = id
      getRoleOne(id).then(response => {
        console.log(response)
        response.data.forEach((item, index) => {
          this.checkedRole.push(item.id)
        })
        this.openTree = true
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRole(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addRole(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    // 权限提交
    submitFormTree() {
      const res = this.$refs.formTree.getCheckedKeys().concat(this.$refs.formTree.getHalfCheckedKeys())
      console.log(res)
      const data = []
      res.forEach(item => {
        data.push({
          roleId: this.form.id,
          moduleId: item
        })
      })
      addRoleOne(data).then((response) => {
        this.msgSuccess('权限修改成功')
        this.openTree = false
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除角色名称为"' + row.roleName + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delRole(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {})
    }
  }
}
</script>
